<template>
  <div id="app" ref="app">
    <transition :name="transitionName">
      <router-view class="Router" />
    </transition>
  </div>
</template>

<script>
export default {
  data() {
    return {
      transitionName: 'slide-right' // 默认动态路由变化为slide-right
    }
  },
  watch: {
    $route(to, from) {
      const isBack = this.$router.isBack //  监听路由变化时的状态为前进还是后退
      if (!isBack) {
        this.transitionName = 'slide-right'
      } else {
        this.transitionName = 'slide-left'
      }
      this.$router.isBack = false
    }
  },
  created() {
    window.removeEventListener('popstate', this.popstateHandler, this)
    window.addEventListener('popstate', this.popstateHandler, this)
  },
  methods: {
    popstateHandler() {
      this.$refs.app.scrollTo(0, 0)
    }
  }
}
</script>

<style>
.Router {
  position: absolute;
  width: 100%;
  transition: all 0.5s ease;
}

.slide-left-enter,
.slide-right-leave-active {
  opacity: 0;
  -webkit-transform: translate(100%, 0);
  transform: translate(100%, 0);
}

.slide-left-leave-active,
.slide-right-enter {
  opacity: 0;
  -webkit-transform: translate(-100%, 0);
  transform: translate(-100% 0);
}
</style>

<style lang="scss">
html,
body {
  margin: 0;
}
* {
  box-sizing: border-box;
  user-select: none;
}
img {
  max-width: 100%;
  pointer-events: none;
  vertical-align: middle;
}
#app {
  max-width: 640px;
  height: calc(100vh);
  margin: auto;
  position: relative;
  overflow-x: hidden;
  overflow-y: scroll;
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: #000;
  color: #2c3e50;
}
</style>
